package cn.jjxx.modules.sys.controller;

import cn.jjxx.core.common.entity.ZtreeEntity;
import cn.jjxx.core.common.entity.tree.BootstrapTreeHelper;
import cn.jjxx.core.common.entity.tree.BootstrapTreeNode;
import cn.jjxx.core.common.entity.tree.TreeSortUtil;
import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.QueryPropertyPreFilter;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.JeewebPropertiesUtil;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.sys.entity.Organization;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;

import org.framework.superutil.thirdparty.excel.ExcelDataFormatter;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.framework.superutil.thirdparty.excel.ExcelUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import cn.jjxx.modules.common.bean.UploadExcel;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.utils.UserUtils;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.modules.sys.entity.SysInterfaceType;
import cn.jjxx.modules.sys.service.ISysInterfaceTypeService;
import cn.jjxx.modules.map.service.ICommonMapService;

/**   
 * @Title: 接口类型
 * @Description: 接口类型
 * @author ml
 * @date 2022-03-23 11:11:52
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/sys/sysinterfacetype")
@RequiresPathPermission("sys:sysinterfacetype")
public class SysInterfaceTypeController extends BaseBeanController<SysInterfaceType> {

    @Autowired
    protected ISysInterfaceTypeService sysInterfaceTypeService;
    @Autowired
    protected ICommonMapService commonMapService;

    public SysInterfaceType get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return sysInterfaceTypeService.selectById(id);
        } else {
            return newModel();
        }
    }

	/**
	 * @Description: 根据获取接口类型的实体数据 .<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequiresMethodPermissions("list")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

	/**
	 * @Description: 根据查询条件动态加载接口类型的树数据 .<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
	@ResponseBody
	@RequestMapping(value = "treeData")
	public void treeData(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid,
			@RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		EntityWrapper<SysInterfaceType> entityWrapper = new EntityWrapper<SysInterfaceType>(entityClass);
		entityWrapper.setTableAlias("t.");
		List<SysInterfaceType> treeNodeList = null;
		if (!async) { // 非异步 查自己和子子孙孙
			treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sort(treeNodeList).async(treeNodeList);
		} else { // 异步模式只查自己
			// queryable.addCondition("parentId", nodeid);
			if (ObjectUtils.isNullOrEmpty(nodeid)) {
				// 判断的应该是多个OR条件
				entityWrapper.isNull("parentId");
			} else {
				entityWrapper.eq("parentId", nodeid);
			}
			treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sync(treeNodeList);
		}
		PropertyPreFilterable propertyPreFilterable = new QueryPropertyPreFilter();
		propertyPreFilterable.addQueryProperty("id", "name", "expanded", "hasChildren", "leaf", "loaded", "level",
				"parentId");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		PageJson<SysInterfaceType> pagejson = new PageJson<SysInterfaceType>(treeNodeList);
		String content = JSON.toJSONString(pagejson, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * @Description: 根据页码和每页记录数，以及查询条件动态加载接口类型的数据 .<br>
	 * @param nodeid 节点Id.<br>
	 * @param async 是否异步.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
	@RequestMapping(value = "ajaxTreeList", method ={ RequestMethod.GET, RequestMethod.POST })
	private void ajaxTreeList(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid,
			@RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
			HttpServletRequest request, HttpServletResponse response, PropertyPreFilterable propertyPreFilterable)
			throws IOException {
		EntityWrapper<SysInterfaceType> entityWrapper = new EntityWrapper<SysInterfaceType>(entityClass);
		entityWrapper.setTableAlias("t.");
		List<SysInterfaceType> treeNodeList = null;
		if (!async) { // 非异步 查自己和子子孙孙
			treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sort(treeNodeList).async(treeNodeList);
		} else { // 异步模式只查自己
			// queryable.addCondition("parentId", nodeid);
			if (ObjectUtils.isNullOrEmpty(nodeid)) {
				// 判断的应该是多个OR条件
				entityWrapper.isNull("parentId");
			} else {
				entityWrapper.eq("parentId", nodeid);
			}
			treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sync(treeNodeList);
		}
		propertyPreFilterable.addQueryProperty("id", "expanded", "hasChildren", "leaf", "loaded", "level", "parentId");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		PageJson<SysInterfaceType> pagejson = new PageJson<SysInterfaceType>(treeNodeList);
		String content = JSON.toJSONString(pagejson, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * @Description: 根据查询条件动态加载接口类型的适合于bootstrapTree的数据 .<br>
	 * @param nodeid 节点Id.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
	@RequestMapping(value = "bootstrapTreeData")
	private void bootstrapTreeData(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid, HttpServletRequest request,
			HttpServletResponse response, PropertyPreFilterable propertyPreFilterable) throws IOException {
		EntityWrapper<SysInterfaceType> entityWrapper = new EntityWrapper<SysInterfaceType>(entityClass);
		entityWrapper.setTableAlias("t.");
		List<SysInterfaceType> treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
		List<BootstrapTreeNode> bootstrapTreeNodes = BootstrapTreeHelper.create().sort(treeNodeList);
		propertyPreFilterable.addQueryProperty("text", "href", "tags", "nodes");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		String content = JSON.toJSONString(bootstrapTreeNodes, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * @Description: 跳转至接口类型的添加界面 .<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }
    
	/**
	 * @Description: 新增接口类型的数据 .<br>
	 * @param sysInterfaceType 接口类型实体类.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") SysInterfaceType sysInterfaceType, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(sysInterfaceType, request, response, result);
    }

	/**
	 * @Description: 跳转至接口类型的更新界面 .<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        SysInterfaceType sysInterfaceType = get(id);
        model.addAttribute("data", sysInterfaceType);
        return display("edit");
    }

	/**
	 * @Description: 修改接口类型的数据 .<br>
	 * @param sysInterfaceType 接口类型实体类.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") SysInterfaceType sysInterfaceType, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(sysInterfaceType, request, response, result);
    }

	/**
	 * @Description: 执行保存接口类型的数据操作 .<br>
	 * @param sysInterfaceType 接口类型实体类.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(SysInterfaceType sysInterfaceType, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(sysInterfaceType, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(sysInterfaceType.getId())) {
                sysInterfaceTypeService.insert(sysInterfaceType);
            } else {
                sysInterfaceTypeService.insertOrUpdate(sysInterfaceType);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

	/**
	 * @Description: 单条删除接口类型 .<br>
	 * @param id 单据Id.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        TableName table = SysInterfaceType.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
        	List<String> ids = Arrays.asList(id.split(","));
        	//得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("删除失败,"+quoteMsg);
				return ajaxJson;
			}
            sysInterfaceTypeService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 执行保存接口类型的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("批量删除成功");
        TableName table = SysInterfaceType.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            //得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("批量删除失败,"+quoteMsg);
				return ajaxJson;
			}
            sysInterfaceTypeService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("批量删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 跳转至接口类型的查看界面 .<br>
	 * @param id 单据Id.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        SysInterfaceType sysInterfaceType = get(id);
        model.addAttribute("data", sysInterfaceType);
        return display("edit");
    }

	/**
	 * @Description: 验证接口类型功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author ml .<br>
	 * @date 2022-03-23 11:11:52.<br>
	 */
    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<SysInterfaceType> entityWrapper = new EntityWrapper<SysInterfaceType>(entityClass);
            valid = sysInterfaceTypeService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }

    /**
     * @Description: 得到可以被审核的单据 .<br>
     * @param bills 单据Id集合.<br>
     * @param status 可操作状态.<br>
     * @author ml .<br>
     * @date 2022-03-23 11:11:52 .<br>
     */
    private List<String> getAllowOptBills(List<String> bills,String status){
    	EntityWrapper<SysInterfaceType> wrapper = new EntityWrapper<SysInterfaceType>();
    	wrapper.in("id", bills);
    	wrapper.eq("status", status);
    	List<SysInterfaceType> list = sysInterfaceTypeService.selectList(wrapper);
    	bills = new ArrayList<String>();
    	for(SysInterfaceType bean:list){
    		bills.add(bean.getId());
    	}
    	return bills;
    }

	/**
	 * 获取ztree格式的数据
	 * @param request req
	 * @param response rep
	 * @param queryable queryable
	 * @param wrapper wrapper
	 * @param nodeId id
	 * @param async id
	 */
	@RequestMapping(value = "getZtree", method ={ RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void getZtree(HttpServletRequest request, HttpServletResponse response,
							Queryable queryable, EntityWrapper<Organization> wrapper, String nodeId, boolean async){
		EntityWrapper<SysInterfaceType> entityWrapper = new EntityWrapper<SysInterfaceType>(entityClass);
		entityWrapper.setTableAlias("t.");
		entityWrapper.orderBy("t.parent_ids");
		List<SysInterfaceType> treeNodeList = null;
		if (!async) { // 非异步 查自己和子子孙孙
			treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sort(treeNodeList).async(treeNodeList);
		} else {
			// 异步模式只查自己
			if (ObjectUtils.isNullOrEmpty(nodeId)) {
				// 判断的应该是多个OR条件
				entityWrapper.isNull("parentId");
			} else {
				entityWrapper.eq("parentId", nodeId);
			}
			treeNodeList = sysInterfaceTypeService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sync(treeNodeList);
		}
		List<ZtreeEntity> ztreeList = getZtreeList(treeNodeList);
		String content = JSON.toJSONString(ztreeList);
		StringUtils.printJson(response, content);
	}

	public List<ZtreeEntity> getZtreeList(List<SysInterfaceType> list){
		List<ZtreeEntity>  ztreeList = new ArrayList<ZtreeEntity>();
		for (SysInterfaceType item : list) {
			ZtreeEntity  zt = new ZtreeEntity();
			zt.setId(item.getId());
			zt.setTitle(item.getName());
			zt.setName(item.getName());
			zt.setPid(item.getParentId());
			zt.setIsParent(item.isHasChildren());
			ztreeList.add(zt);
		}
		return ztreeList;
	}
}
